package com.juli.v2xdemo.activity;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.cz.basetool.CodeTool;
import com.github.capur16.digitspeedviewlib.DigitSpeedView;
import com.github.florent37.viewanimator.ViewAnimator;
import com.juli.v2xdemo.PlaneWar;
import com.juli.v2xdemo.R;
import com.juli.v2xdemo.entity.CarInfo;
import com.juli.v2xdemo.entity.MessageEvent;
import com.juli.v2xdemo.presenter.TcpPresenter;
import com.juli.v2xdemo.util.CoodUtils;
import com.juli.v2xdemo.util.GPSutils;
import com.juli.v2xdemo.util.MyCar_Utils;
import com.juli.v2xdemo.util.OtherCar_Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class MainActivity2 extends Activity {

    @BindView(R.id.car)
    ImageView car;
    @BindView(R.id.tv_connect)
    TextView tv_connect;

    @BindView(R.id.iv_carwarn)
    ImageView ivCarwarn;
    @BindView(R.id.che)
    ImageView che;
    @BindView(R.id.mountain)
    ImageView mountain;
    @BindView(R.id.tv_juli)
    TextView tvJuli;
    @BindView(R.id.tv_carWarn)
    TextView tv_carWarn;
    @BindView(R.id.digit_speed_view)
    DigitSpeedView digitSpeedView;
    @BindView(R.id.iv_traffic)
    ImageView ivTraffic;
    @BindView(R.id.tv_traffic)
    TextView tvTraffic;
    @BindView(R.id.layout_traffic_sign)//交通标志
            LinearLayout layouTrafficSign;

    private PlaneWar planeWar;

    TcpPresenter tcpPresenter;

    private CountDownTimer timer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        planeWar = (PlaneWar) View.inflate(this, R.layout.activity_main2, null);
        setContentView(planeWar);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        planeWar.start();

//        tcpPresenter = new TcpPresenter(this, new TcpActionCallBack(this), new TcpUICallBackImpl(this, tv_connect));
//        PresenterManager.getInstance().registTcpPresenter(tcpPresenter);
//        PresenterManager.getInstance().init();
//        tcpPresenter.send();


        mountain.setVisibility(View.GONE);

        MyCar_Utils.add_mycar(planeWar, this);
        OtherCar_Utils.add_othercar(planeWar, this);


//假的初shi数据
        //
        Glide.with(MainActivity2.this).load(R.drawable.ic_hfmqyj).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivCarwarn);
//        Glide.with(MainActivity2.this).load(R.drawable.che1).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(car);

        layouTrafficSign.setVisibility(View.VISIBLE);
        ivTraffic.setImageResource(R.drawable.ic_lh);
        tvTraffic.setText("路滑");
        Spannable string = new SpannableString("前方" + 100 + "米");
        string.setSpan(new AbsoluteSizeSpan(70), 2, string.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        tvJuli.setText(string);



//        ivTraffic.setVisibility(View.VISIBLE);
//        ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.ic_straight_light_warn));
//        tvTraffic.setText("直行红灯预警");

//        trafficLightSecondstartTimer(5,"红灯");
//        timer.start();

    }
    private void carWarnType(int drawableSource,String carwarnName){
        Glide.with(MainActivity2.this).load(drawableSource).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(ivCarwarn);
        tv_carWarn.setText(carwarnName);
    }

///////////

    /**
     * 订阅者处理事件   将数据显示到页面上
     */

    public void onEventMainThread(MessageEvent event) {
        Log.e("MessageEvent", "xxxx");

        if (!TextUtils.isEmpty(event.getType())) {
            switch (event.getType()) {
                case "data":
                    if (!TextUtils.isEmpty(event.getType())) {

                        Log.e("MessageEvent", "event" + event.getMessage());
                        CarInfo carData = event.getCarInfo();
                        String vehichlInfo = carData.getVehichlInfo();

                        String lat_long_dir = carData.getLat_Long_Dir();


                        String vehichlInfo8 = CodeTool.oneByteHexNum2BinaryStr8(vehichlInfo);
                        String isme = vehichlInfo8.substring(0, 1);
                        String early_warning = vehichlInfo8.substring(1, 8);


                        if (isme.equals("0")) {
                            //自己
                            //预警
                            String carWarnStr = "";
                            if (early_warning.equals("0000000")) {
                                Log.e("预警", "无预警");
//                                ivVehicleWarn.setVisibility(View.INVISIBLE);
//                                ivVehicleWarn.setImageDrawable(getResources().getDrawable(R.drawable.ic_straight_light_warn));
                            } else if (early_warning.equals("0000001")) {
//                                ivVehicleWarn.setVisibility(View.VISIBLE);
//                                ivVehicleWarn.setImageDrawable(getResources().getDrawable(R.drawable.ic_straight_light_warn));
                                carWarnStr = "前方车辆碰撞预警";
                                Log.e("预警", "前方车辆碰撞预警");

                            } else if (early_warning.equals("0000010")) {


//                                ivVehicleWarn.setVisibility(View.VISIBLE);
//                                ivVehicleWarn.setImageDrawable(getResources().getDrawable(R.drawable.ic_straight_light_warn));
                                carWarnStr = "后方盲区超车预警";
                                Log.e("预警", "后方盲区超车预警");
                            } else if (early_warning.equals("0000100")) {
//                                ivVehicleWarn.setVisibility(View.VISIBLE);
//                                ivVehicleWarn.setImageDrawable(getResources().getDrawable(R.drawable.ic_straight_light_warn));

                                carWarnStr = "紧急车辆预警";
                                Log.e("预警", "紧急车辆预警");

                            } else if (early_warning.equals("0001000")) {

//                                ivVehicleWarn.setVisibility(View.VISIBLE);
//                                ivVehicleWarn.setImageDrawable(getResources().getDrawable(R.drawable.ic_straight_light_warn));

                                carWarnStr = "故障车辆预警预警";
                                Log.e("预警", "故障车辆预警预警");
                            }
                            tv_carWarn.setText(carWarnStr);


                            //经度
                            String latitude = GPSutils.longitudeandlatitude(carData.getLatitude());
                            //纬度
                            String longitude = GPSutils.longitudeandlatitude(carData.getLongitude());

                            Log.e("纬度latitude", "" + latitude);
                            Log.e("经度longitude", "" + longitude);
                            //经纬度方向
                            String Lat_Long_Dir = carData.getLat_Long_Dir();
                            String Lat_Long_Dir8 = CodeTool.oneByteHexNum2BinaryStr8(Lat_Long_Dir);
                            Log.e("经纬度方向Lat_Long_Dir8", Lat_Long_Dir8);
                            String Heading = carData.getHeading();
                            Log.e("车辆航向角Heading", Heading);
                            //速度
                            String Speed = carData.getSpeed();
                            String sudu = CoodUtils.Sudu(Speed);
                            float d = Float.parseFloat(sudu);

                            Log.e("速度sudu", sudu);

                            digitSpeedView.updateSpeed((int) d);

                            String AlertType = carData.getAlertType();
                            String baty1 = AlertType.substring(0, 2);
                            String baty2 = AlertType.substring(2, 4);
                            String baty28 = CodeTool.oneByteHexNum2BinaryStr8(baty2);
                            Log.e("路测警示AlertType", baty28);
                            int v = Integer.parseInt(baty1);
                            AlertType_Byte1(v);
                            AlertType_Byte2(baty28);
                            //警示信息距离
                            String description = carData.getDescription();


                            description(type,description);
                            //车道数目
                            String Lane_num = carData.getLane_num();
                            //当前车辆所在车道
                            String veh_lane = carData.getVeh_Lane();
                            Log.e("我车车道", "" + veh_lane);

                        } else {
                            //当前车辆所在车道
                            String veh_lane = carData.getVeh_Lane();

                            //別人
                        }
                        Log.e("MessageEvent", "event:" + vehichlInfo8);

                    } else {
                        Log.e("MessageEvent", "event数据为空");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //0为无预警  1警示信息的距离，2为红灯预警 ，3为限速预警
    int type = 0;

    public void AlertType_Byte1(int early_warning) {
        switch (early_warning) {
            case 0:
                layouTrafficSign.removeAllViews();
                layouTrafficSign.setVisibility(View.GONE);
                Log.e("路测警示", "无预警");
                type = 0;
                break;
            case 37:
                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_zywx);
                tvTraffic.setText("危险");
                Log.e("路测警示", "危险");
                type = 1;
                break;
            case 15:
                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_zyls);
                tvTraffic.setText("落石");
                Log.e("路测警示", "落石");
                type = 1;
                break;
            case 02:

                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_jw);
                tvTraffic.setText("急弯");
                Log.e("路测警示", "急弯");
                type = 1;
                break;
            case 38:

                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_sg);
                tvTraffic.setText("正在施工");
                Log.e("路测警示", "正在施工");
                type = 1;
                break;
            case 17:

                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_lh);
                tvTraffic.setText("路滑");
                Log.e("路测警示", "路滑");
                type = 1;
                break;
            case 21:

                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_sd);
                tvTraffic.setText("隧道");
                Log.e("路测警示", "隧道");
                type = 1;
                break;
            case 27:
                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_zywx);
                tvTraffic.setText("注意危险");
                Log.e("路测警示", "注意危险");
                type = 1;
                break;
            case 85:
                layouTrafficSign.setVisibility(View.VISIBLE);
                ivTraffic.setImageResource(R.drawable.ic_xs);
                tvTraffic.setText("限速");
                Log.e("路测警示", "限速");
                type = 1;
                break;

            default:
                break;
        }

    }

    public void AlertType_Byte2(String early_warning) {

        String roadWarnStr = "";
        if (early_warning.substring(0, 1).equals("1")) {
            intersection();
            roadWarnStr = "交叉路口碰撞预警";
            ivTraffic.setVisibility(View.VISIBLE);
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.timg));
            Log.e("路测警示", "交叉路口碰撞预警");
            type = 1;
        } else {
            intersection();
            safe();
            Log.e("路测警示", "交叉路口无预警");
            type = 0;
        }

        if (early_warning.substring(1, 2).equals("1")) {
            intersection();

            roadWarnStr ="直行红灯预警";
            ivTraffic.setVisibility(View.VISIBLE);
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.ic_straight_light_warn));
            Log.e("路测警示", "直行红灯预警");
            type = 2;
        } else {
            intersection();
            safe();
            Log.e("路测警示", "直行闯红灯无预警");
            type = 0;
        }
        if (early_warning.substring(2, 3).equals("1")) {
            intersection();
            roadWarnStr ="左转红灯预警";
            ivTraffic.setVisibility(View.VISIBLE);
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.ic_leftlight_warn));
            Log.e("路测警示", "左转红灯预警");
            type = 2;
        } else {
            intersection();
            safe();
            Log.e("路测警示", "左转闯红灯无预警");
            type = 0;
        }
        if (early_warning.substring(3, 4).equals("1")) {
            intersection();

            roadWarnStr ="右转红灯预警";
            ivTraffic.setVisibility(View.VISIBLE);
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.ic_rightlight_warn));
            Log.e("路测警示", "右转闯红灯预警");
            type = 2;
        } else {
            intersection();
            safe();
            Log.e("路测警示", "右转闯红灯无预警");
            type = 0;
        }
        if (early_warning.substring(4, 5).equals("1")) {

            roadWarnStr = "前方行人预警";
            ivTraffic.setVisibility(View.VISIBLE);
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.ic_infront_people_warn));
            Log.e("路测警示", "前方行人预警");
            type = 1;
        } else {
            safe();
            Log.e("路测警示", "方行人无预警");
            type = 0;
        }
        if (early_warning.substring(5, 6).equals("1")) {

            roadWarnStr ="限速预警";
            ivTraffic.setVisibility(View.VISIBLE);
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.ic_speed_limit_warn));
            Log.e("路测警示", "限速预警");
            type = 3;
        } else {
            safe();
            Log.e("路测警示", "限速无预警");
            type = 0;
        }
        tvTraffic.setText(roadWarnStr);
    }

    /**
     * 路况无预警
     */
    private void safe() {
        ivTraffic.setVisibility(View.GONE);
        tv_carWarn.setText("无预警");
    }

    /**
     * 路况需要路口
     */
    private void intersection() {
        mountain.setImageDrawable(getResources().getDrawable(R.drawable.v10));
//        tishi.setTextColor(getResources().getColor(R.color.red));
        ViewAnimator.animate(mountain)
                .translationY(-1000, 1800)
                .interpolator(new DecelerateInterpolator())
                .duration(20000)
                .start();
    }
    /**
     * 不同的AlertType对应不同的 Description显示的内容
     *
     * @param type
     */
    public void description(int type,String descriptionStr) {
        if (type == 0) {
            //路况无预警

        } else if (type == 1) {
            //警示信息的距离(米)
            long parseLong = Long.parseLong(descriptionStr, 16);
            Log.e("路测警示距离", "" + parseLong);
            Spannable string = new SpannableString("前方" + parseLong + "米");
            string.setSpan(new AbsoluteSizeSpan(70), 2, string.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            tvJuli.setText(string);
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.timg));//交叉路口碰撞路预警没涂
        } else if (type == 2) {
            String lightStr = "";
            //红灯预警
            String baty1 = descriptionStr.substring(0, 2);//baty1倒计时单位
            long l = Long.parseLong(baty1);
            if (l == 1) {
                lightStr = "红灯";
                Log.e("红灯警示", "");
            } else if (l == 2) {
                //黄灯
                lightStr = "黄灯";
                Log.e("黄灯警示", "");
            } else if (l == 3) {
                //绿灯
                lightStr = "绿灯";
                Log.e("绿灯警示", "");
            }
            String baty2 = descriptionStr.substring(2, 4);
            //倒计时时间
            long l2 = Long.parseLong(baty2);
            Log.e("警示倒计时", "" + l2);

            trafficLightSecondstartTimer(Integer.valueOf(baty1),lightStr);
            timer.start();


        } else if (type == 3) {
            //限速类型
            String baty1 = descriptionStr.substring(0, 2);
            int v = Integer.parseInt(baty1);

            String speedlimitStr = "";

            //限速预警
            switch (v) {
                case 0:
                    Log.e("限速预警", "无限速");
                    break;
                case 1:
                    speedlimitStr = "学校区域限速";
                    Log.e("限速预警", "学校区域限速");
                    break;
                case 2:
                    speedlimitStr = "学校放学时的最大速度";
                    Log.e("限速预警", "学校放学时的最大速度");
                    break;
                case 3:
                    speedlimitStr = "建筑区域最大速度";
                    Log.e("限速预警", "建筑区域最大速度");
                    break;
                case 4:
                    speedlimitStr = "乘用车最小速度";
                    Log.e("限速预警", "乘用车最小速度");
                    break;
                case 5:
                    speedlimitStr = "乘用车最大速度";
                    Log.e("限速预警", "乘用车最大速度");
                    break;
                case 6:
                    speedlimitStr = "乘用车夜晚最大速度";
                    Log.e("限速预警", "乘用车夜晚最大速度");
                    break;
                case 7:
                    speedlimitStr = "卡车最小速度";
                    Log.e("限速预警", "卡车最小速度");
                    break;
                case 8:
                    speedlimitStr = "卡车最大速度";
                    Log.e("限速预警", "卡车最大速度");
                    break;
                case 9:
                    speedlimitStr = "卡车夜晚最大速度";
                    Log.e("限速预警", "卡车夜晚最大速度");
                    break;
                case 10:
                    speedlimitStr = "出租车最小速度";
                    Log.e("限速预警", "出租车最小速度");
                    break;
                case 11:
                    speedlimitStr = "出租车最大速度";
                    Log.e("限速预警", "出租车最大速度");
                    break;
                case 12:
                    speedlimitStr = "出租车最夜晚大速度";
                    Log.e("限速预警", "出租车最夜晚大速度");
                    break;

                default:
                    break;
            }
            //限时速度
            String baty2 = descriptionStr.substring(2, 4);
            int v2 = Integer.parseInt(baty2);
            Log.e("限速", "" + v2);
            tvJuli.setText(speedlimitStr + v + "km/h");
            ivTraffic.setImageDrawable(getResources().getDrawable(R.drawable.ic_speed_limit_warn));

        }

    }



    /**
     * 交通信号灯计时器
     * @param second 秒
     * @param lightStr 红/黄/lu灯
     */


    private void trafficLightSecondstartTimer(int second, final String lightStr) {

        timer = new CountDownTimer(second * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                tvJuli.setText(lightStr+(millisUntilFinished / 1000) + "S");
                //放置图片
                Drawable nav_up=getResources().getDrawable(R.drawable.ic_redlight);
                nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                tvJuli.setCompoundDrawables(null, null, nav_up, null);
            }

            @Override
            public void onFinish() {
                tvJuli.setText("");
                tvJuli.setGravity(View.TEXT_ALIGNMENT_CENTER);
                tvJuli.setCompoundDrawables(null,null,null,null);

            }
        };
    }

    //取消倒计时
    public void oncancel(View v) {
        timer.cancel();
    }

    // 开始倒计时
    public void restart(View v) {
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
